package com.tanhua.bg.login.Interceptor;


import com.tanhua.bg.login.config.LoginThreadLocal;
import com.tanhua.bg.login.pojo.Login;
import com.tanhua.bg.login.service.LoginService;
import com.tanhua.common.utils.NoAuthorization;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class UserTokenInterceptor implements HandlerInterceptor {

    @Autowired
    private LoginService loginService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //校验handler是否是HandlerMethod
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        //判断是否包含@NoAuthorization注解，如果包含，直接放行
        if (((HandlerMethod) handler).hasMethodAnnotation(NoAuthorization.class)) {
            return true;
        }

        //从请求头中获取token
        String token = request.getHeader("Authorization");
        if (StringUtils.isNotEmpty(token)){
            Login login = this.loginService.queryUserByToken(token);
            if (login!=null){
                LoginThreadLocal.set(login);
                return true;
            }
        }
        //token无效
        response.setStatus(401);//无权访问
        return false;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //从ThreadLocal中移除User对象
        LoginThreadLocal.remove();
    }
}
